import Main from '@/components/main'
import axios from '@/libs/api.request'
import { forEach } from '@/libs/tools'
import { hasChild } from '@/libs/util'
import parentView from '@/components/parent-view'

// 初始化路由
export const initRouter = (vm) => {
    let list = []

    axios.request({
        url: 'account/menu',
        method: 'get'
    }).then(res => {
        var menuData = res.data
        list = formatMenu(menuData)
        vm.$store.commit('refreshMenuList', list)
    });

    return list
}

/**
 * 加载菜单，在创建路由时使用
 */
export const loadMenu = () => {
    let list = []
    axios.request({
        url: 'account/menu',
        method: 'get'
    }).then(res => {
        var menuData = res.data
        list = formatMenu(menuData)
    });

    return list
}

/**
 * 格式化菜单
 * @param {*} list
 */
export const formatMenu = (list) => {
    let res = []
    forEach(list, item => {
        let obj = {
            path: item.path,
            name: item.name,
            icon: (item.meta && item.meta.icon) || ''
        }
        obj.meta = item.meta
        if (item.parentId === "0") {
            obj.component = Main
        } else {
            let data = item.component
            if (item.children.length > 0) {
                obj.component = parentView
            } else {
                obj.component = () =>
                    import ('@/view' + data)
            }
        }
        if (hasChild(item)) {
            obj.children = formatMenu(item.children)
        }
        res.push(obj)
    })
    return res
}